/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkeddata.arida.ufc.br.manager.impl;

import com.hp.hpl.jena.query.ParameterizedSparqlString;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFormatter;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.validator.routines.UrlValidator;

/**
 *
 * @author jeovane
 */
public class ExecuteQueryJena {

    private String endpoint;
    private String queryString;
    private QueryExecution queryExecution;
    private Query query;
    private ParameterizedSparqlString sparqlString;
    private String[] schemes = {"http", "https"};
    private UrlValidator urlValidator = new UrlValidator(schemes);
    private List<String> parameterList = new ArrayList<String>();

    public void setParameterList(String parameterList) {
        this.parameterList.add(parameterList);
    }

    public ExecuteQueryJena(String endpoint, String queryString) {
        this.endpoint = endpoint;
        this.queryString = queryString;
    }

    private ResultSet resultSetQuery() throws Exception {
        sparqlString = new ParameterizedSparqlString(this.queryString);

        for (int i = 0; i < parameterList.size(); i++) {
            String[] setLiteral = parameterList.get(i).split(",", 2);
            if (urlValidator.isValid(setLiteral[1])) {
                sparqlString.setIri(setLiteral[0].toLowerCase(), setLiteral[1]);
            } else {
                sparqlString.setLiteral(setLiteral[0].toLowerCase(), setLiteral[1]);
            }
        }

        query = QueryFactory.create(sparqlString.toString());
        queryExecution = QueryExecutionFactory.sparqlService(this.endpoint, query);
        ResultSet result = queryExecution.execSelect();
        return result;
    }

    public String printQueryXML() throws Exception {
        try {
            if (resultSetQuery().hasNext()) {
                return ResultSetFormatter.asXMLString(resultSetQuery());
            }
        } catch (Exception e) {
            return e.getMessage();
        } finally {
            queryExecution.close();
        }

        return ResultSetFormatter.asXMLString(resultSetQuery());
    }

    public String printQueryJSON() throws Exception {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        ResultSetFormatter.outputAsJSON(stream, resultSetQuery());
        String queryJson = stream.toString();
        queryExecution.close();
        return queryJson;
    }
    
    public List<String> ListQuerySelect() throws Exception {
        return resultSetQuery().getResultVars();
    }
}
